package org.streets.wicket.internal;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

//TODO maybe error on download file
public class ServletResponseWrapper extends HttpServletResponseWrapper {

	private InnerPrintWriter writer;
	private ByteArrayOutputStream output;
	private String charset;

	public ServletResponseWrapper(HttpServletResponse httpServletResponse,
			String charset) {
		super(httpServletResponse);
		this.output = new ByteArrayOutputStream();
		this.writer = new InnerPrintWriter(output);
		this.charset = charset;
	}

	public void finalize() throws Throwable {
		super.finalize();
		output.close();
		writer.close();
	}

	public String getContent() {
		try {
			writer.flush(); // 刷新该流的缓冲，详看java.io.Writer.flush()
			String content = writer.getByteArrayOutputStream().toString();
			// 此处可根据需要进行对输出流以及Writer的重置操作
			// 比如tmpWriter.getByteArrayOutputStream().reset()
			return content;
		} catch (Exception e) {
			return "UnsupportedEncoding";
		}
	}

	// 覆盖getWriter()方法，使用我们自己定义的Writer
	public PrintWriter getWriter() throws IOException {
		return writer;
	}

	public void close() throws IOException {
		writer.close();
	}

	// 自定义PrintWriter，为的是把response流写到自己指定的输入流当中
	// 而非默认的ServletOutputStream
	private static class InnerPrintWriter extends PrintWriter {
		
		ByteArrayOutputStream myOutput; // 此即为存放response输入流的对象

		public InnerPrintWriter(ByteArrayOutputStream output) {
			super(output);
			myOutput = output;
		}

		public ByteArrayOutputStream getByteArrayOutputStream() {
			return myOutput;
		}
	}
}